#!/bin/bash

export PTXDIST_SYSROOT_HOST=$(ptxd_get_ptxconf PTXCONF_SYSROOT_HOST)
# FIXME: Is there a dedicated IMAGEDIR?
export IMAGEDIR=${PTXDIST_PLATFORMDIR}/images
TST="${1}"
shift

[ -e "${PTXDIST_BOARDSETUP}" ] || ptxd_bailout "Please run 'ptxdist boardsetup' first!"

ptxd_get_path \
	"${PTXDIST_PLATFORMCONFIGDIR}/tests/${TST}.kermit" \
	"${PTXDIST_WORKSPACE}/tests/${TST}.kermit" \
	"${PTXDIST_TOPDIR}/tests/${TST}.kermit" ||
ptxd_bailout "No kermit-script for ${TST} found! Please report to the developers."
KSCRIPT="${ptxd_reply}"

ptxd_get_path \
	"${PTXDIST_PLATFORMCONFIGDIR}/tests/libptxdisttest.kermit" \
	"${PTXDIST_WORKSPACE}/tests/libptxdisttest.kermit" \
	"${PTXDIST_TOPDIR}/tests/libptxdisttest.kermit" ||
ptxd_bailout "Could not find kermit-library! Please report to the developers."
LIB_PATH="$(dirname ${ptxd_reply})"

TMPFILE="$(mktemp "${PTXDIST_TEMPDIR}/kwrapper.XXXXXX")"

#
# we _must_ set the variables in kermit using 'define'!
# '.' has a bug there (patch already mainlined).
#
sed -e 's/^\(PTXCONF_BOARDSETUP_[A-Z0-9_]*\)=/define \1 /' "${PTXDIST_BOARDSETUP}" > "${TMPFILE}"
# FIXME: add PTXDIST_TEST_vars from environment, too

ckermit "${KSCRIPT}" -Y = "${LIB_PATH}" "${TMPFILE}" "${@}" ||
echo "An error occured! Please check also .${PTXDIST_PLATFORMDIR#${PTXDIST_WORKSPACE}}/test.log for further details!" >&2

rm -f "${TMPFILE}"
